import paramsStore from '@/store/modules/paramsStore';
import { doUpdateOrderPriority } from '@/api/demand/arithmetic/index';
import { message } from '@/components/q-message/message';
import type { OrderListRecord } from '@/api/demand/order/model/type';
import type { SchedulingStatus } from '@/api/demand/arithmetic/model/type';
import router from '@/router';

export default (tableRef?: Ref<TableRef | undefined>) => {
    /**
     * @: 订单优先级
     */
    const priorityChange = async (val: number, row: OrderListRecord) => {
        const orderPriority = row.orderPriority;
        row.orderPriority = val;
        try {
            await doUpdateOrderPriority({ id: row.id, orderPriority: val });
            message.success('更新订单优先级成功！');
        } catch (error) {
            row.orderPriority = orderPriority;
            console.log('error');
        }
    };

    /**
     * @: 排程运算默认排序
     */
    const getAddedParams = (schedulingStatus: SchedulingStatus) => {
        return {
            schedulingStatus,
            orders: [{ column: 'planned_start_time', asc: false }]
        };
    };

    /**
     * @: 跳转到物料管理
     */
    const { setMaterialCode } = paramsStore();
    const jumpToMaterial = (itemCode: string) => {
        setMaterialCode(itemCode);
        router.push('/materialsManagement');
    };

    /**
     * @: 弹框处理完成重新获取数据并且清空勾选项
     */
    const handleGetData = () => {
        tableRef?.value?.getData?.();
        tableRef?.value?.clearSelection();
    };

    /**
     * @: 更新选中数据
     */
    const updateSelect = (orderNumber: string[]) => {
        // 全部选中的id
        const selectRow: OrderListRecord[] = tableRef?.value?.elTable?.getSelectionRows();
        // 需要更新的表格行
        const updateRow = selectRow.filter(item => orderNumber.includes(item.orderNumber));

        updateRow.forEach(item => {
            tableRef?.value?.elTable?.toggleRowSelection(item, false);
        });

        tableRef?.value?.getData();
    };

    return {
        priorityChange,
        getAddedParams,
        jumpToMaterial,
        handleGetData,
        updateSelect
    };
};
